<?php

$message = new Message('0.0.0.0', 9500, 2, true);
$message->start();

class Message
{
    public $server;

    public function __construct($ip, $port, $worker_num = 2, $daemonize = false, $log_file = '/usr/share/nginx/html/im/swoole.log')
    {
        $this->server = new swoole_websocket_server($ip, $port);

        //配置服务器信息


        $this->server->set(array(
            'worker_num' => $worker_num,
            'daemonize'=>$daemonize,
            // 'log_file' =>$log_file
        ));
    }

    public function start()
    {
        //打开连接
        $this->server->on('Open', function ($server, $req) {
        });

        $this->server->on('Message', function ($server, $frame) {
            $msg = "{$frame->data}";
            $name = explode(':', $msg);
            //redis
            if ($name[0] == 'name') {
                $num = '欢迎' . $name[1] . '进入聊天室，当前在线人数' . count($server->connection_list()) . '人';
                $server->push($frame->fd, $num, true);
            } else {
                foreach ($server->connection_list() as $fd) {
                    $server->push($fd, $frame->data, true);
                }
            }
        });

        //关闭连接
        $this->server->on('Close', function ($server, $fd) {
            ;
        });

        $this->server->start();
    }
}


